<?php
class ProductController extends Controller
{
  /**
   * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
   * using two-column layout. See 'protected/views/layouts/column2.php'.
   */
  public $layout = '//layouts/column2';
  
  /**
   * @return array action filters
   */
  public function filters()
  {
    return array(
      'accessControl' // perform access control for CRUD operations
      //'postOnly + delete' // we only allow deletion via POST request
    );
  }
  
  /**
   * Specifies the access control rules.
   * This method is used by the 'accessControl' filter.
   * @return array access control rules
   */
  public function accessRules()
  {
    return array(
      array(
        'allow', // allow authenticated user to perform 'create' and 'update' actions
        'actions' => array(
          'index',
          'view',
          'create',
          'update',
          'delete',
          'deleteimage'
        ),
        'users' => array(
          '@'
        )
      ),
      array(
        'deny', // deny all users
        'users' => array(
          '*'
        )
      )
    );
  }
  
  /**
   * Displays a particular model.
   * @param integer $id the ID of the model to be displayed
   */
  public function actionView($id)
  {
    $model      = $this->loadModel($id);
    $model_lang = $this->loadModelLang($id, Yii::app()->session['language']);
    $this->render('view', array(
      'model' => $model,
      'model_lang' => $model_lang
    ));
  }
  
  /**
   * Creates a new model.
   * If creation is successful, the browser will be redirected to the 'view' page.
   */
  public function actionCreate()
  {
    $model          = new Product;
    $model->enabled = 1;
    
    if (isset($_POST['Product'])) {
      $model->attributes  = $_POST['Product'];
      $model->price       = $_POST['Product']['price'];
      $model->color       = $_POST['Product']['color'];
      $model->description = $_POST['Product']['description'];
      $model->detail      = $_POST['Product']['detail'];
      $model->categoryID  = ($model->categoryID == 0) ? '' : $model->categoryID;
      
      $transaction = Yii::app()->db->beginTransaction();
      
      try {
        if ($model->validate()) {
          $model->name2        = ($_POST['Product']['name2'] != '') ? $_POST['Product']['name2'] : '{translate}';
          $model->price2       = ($_POST['Product']['price2'] != '') ? $_POST['Product']['price2'] : '{translate}';
          $model->color2       = ($_POST['Product']['color2'] != '') ? $_POST['Product']['color2'] : '{translate}';
          $model->description2 = ($_POST['Product']['description2'] != '') ? $_POST['Product']['description2'] : '{translate}';
          $model->detail2      = ($_POST['Product']['detail2'] != '') ? $_POST['Product']['detail2'] : '{translate}';
          $model->save();
          foreach (array(
            'vi',
            'en'
          ) as $item) {
            $lang              = new ProductLang();
            $lang->productID   = $model->id;
            $lang->name        = ($item == 'vi') ? $model->name : $model->name2;
            $lang->price       = ($item == 'vi') ? $model->price : $model->price2;
            $lang->color       = ($item == 'vi') ? $model->color : $model->color2;
            $lang->description = ($item == 'vi') ? $model->description : $model->description2;
            $lang->detail      = ($item == 'vi') ? $model->detail : $model->detail2;
            $lang->languageID  = $item;
            
            $lang->save();
          }
          //Save images
          $imgs = CUploadedFile::getInstances($model, "image");
          if ($imgs) {
            foreach ($imgs as $img) {
              $file            = new File();
              $file->filename  = $img->getName();
              $file->filesaved = encodeFilename(time() . '_' . $img->getName());
              $file->filetype  = 'image';
              $file->folder    = 'product/post-images';
              $img->saveAs('upload/product/post-images/' . $file->filesaved);
              $file->save();
              $fileID                  = $file->id;
              $file_product            = new ProductFile();
              $file_product->fileID    = $fileID;
              $file_product->productID = $model->id;
              $file_product->save();
              
              //thumbnail 
              $thumb      = Yii::app()->image->load(Yii::getPathOfAlias("webroot") . "/upload/product/post-images/" . $file->filesaved);
              $thumbnails = Product::model()->thumbnails;
              foreach ($thumbnails as $thumbnail) {
                $thumb->resize($thumbnail[0], $thumbnail[1]);
                $thumb->save(Yii::getPathOfAlias("webroot") . "/upload/product/thumbs_$thumbnail[0]x$thumbnail[1]/" . $file->filesaved); //save vao thumb
              }
            }
          }
          
          $transaction->commit();
          $this->redirect(array(
            'view',
            'id' => $model->id
          ));
        }
      }
      catch (Exception $e) {
        $transaction->rollBack();
      }
    }
    
    $this->render('create', array(
      'model' => $model
    ));
  }
  
  /**
   * Updates a particular model.
   * If update is successful, the browser will be redirected to the 'view' page.
   * @param integer $id the ID of the model to be updated
   */
  public function actionUpdate($id)
  {
    $model               = $this->loadModel($id);
    $vn                  = $this->loadModelLang($id, 'vi');
    $en                  = $this->loadModelLang($id, 'en');
    $model->name         = $vn->name;
    $model->name2        = $en->name;
    $model->price        = $vn->price;
    $model->price2       = $en->price;
    $model->color        = $vn->color;
    $model->color2       = $en->color;
    $model->description  = $vn->description;
    $model->description2 = $en->description;
    $model->detail       = $vn->detail;
    $model->detail2      = $en->detail;
    
    $image = $model->getProductFiles($model->id);
    
    if (isset($_POST['Product'])) {
      $model->attributes  = $_POST['Product'];
      $model->price       = $_POST['Product']['price'];
      $model->color       = $_POST['Product']['color'];
      $model->description = $_POST['Product']['description'];
      $model->detail      = $_POST['Product']['detail'];
      $model->categoryID  = ($model->categoryID == 0) ? '' : $model->categoryID;
      
      $transaction = Yii::app()->db->beginTransaction();
      
      try {
        if ($model->validate()) {
          $model->name2        = ($_POST['Product']['name2'] != '') ? $_POST['Product']['name2'] : $model->name2;
          $model->price2       = ($_POST['Product']['price2'] != '') ? $_POST['Product']['price2'] : '{translate}';
          $model->color2       = ($_POST['Product']['color2'] != '') ? $_POST['Product']['color2'] : '{translate}';
          $model->description2 = ($_POST['Product']['description2'] != '') ? $_POST['Product']['description2'] : $model->description2;
          $model->detail2      = ($_POST['Product']['detail2'] != '') ? $_POST['Product']['detail2'] : '{translate}';
          $model->save();
          $vn->name        = $model->name;
          $vn->price       = $model->price;
          $vn->color       = $model->color;
          $vn->description = $model->description;
          $vn->detail      = $model->detail;
          $vn->update();
          $en->name        = $model->name2;
          $en->price       = $model->price2;
          $en->color       = $model->color2;
          $en->description = $model->description2;
          $en->detail      = $model->detail2;
          $en->update();
          
          //Save images
          $imgs = CUploadedFile::getInstances($model, "image");
          if ($imgs) {
            foreach ($imgs as $img) {
              $file            = new File();
              $file->filename  = $img->getName();
              $file->filesaved = encodeFilename(time() . '_' . $img->getName());
              $file->filetype  = 'image';
              $file->folder    = 'product/post-images';
              $img->saveAs('upload/product/post-images/' . $file->filesaved);
              $file->save();
              $fileID                  = $file->id;
              $file_product            = new ProductFile();
              $file_product->fileID    = $fileID;
              $file_product->productID = $model->id;
              $file_product->save();
              
              //thumbnail 
              $thumb      = Yii::app()->image->load(Yii::getPathOfAlias("webroot") . "/upload/product/post-images/" . $file->filesaved);
              $thumbnails = Product::model()->thumbnails;
              foreach ($thumbnails as $thumbnail) {
                $thumb->resize($thumbnail[0], $thumbnail[1]);
                $thumb->save(Yii::getPathOfAlias("webroot") . "/upload/product/thumbs_$thumbnail[0]x$thumbnail[1]/" . $file->filesaved); //save vao thumb
              }
            }
          }
          
          $transaction->commit();
          $this->redirect(array(
            'view',
            'id' => $model->id
          ));
        }
      }
      catch (Exception $e) {
        $transaction->rollBack();
      }
    }
    
    $this->render('update', array(
      'model' => $model,
      'image' => $image
    ));
  }
  
  public function actionDeleteImage()
  {
    if (Yii::app()->request->isAjaxRequest) {
      $id           = $_GET["id"];
      $product_file = ProductFile::model()->findByAttributes(array(
        'fileID' => $id
      ));
      $file         = File::model()->findByPk($id);
      
      if (!empty($file) && file_exists(Yii::app()->basePath . "/../upload/product/post-images/" . $file->filesaved)) {
        @unlink(Yii::getPathOfAlias("webroot") . "/upload/product/post-images/" . $file->filesaved);
        $thumbnails = Product::model()->thumbnails;
        foreach ($thumbnails as $thumbnail) {
          if (file_exists(Yii::app()->basePath . "/../upload/product/thumbs_$thumbnail[0]x$thumbnail[1]/" . $file->filesaved)) {
            @unlink(Yii::getPathOfAlias("webroot") . "/upload/product/thumbs_$thumbnail[0]x$thumbnail[1]/" . $file->filesaved);
          }
        }
        $product_file->delete();
        $file->delete();
      }
      echo 'success';
    }
  }
  
  /**
   * Deletes a particular model.
   * If deletion is successful, the browser will be redirected to the 'admin' page.
   * @param integer $id the ID of the model to be deleted
   */
  public function actionDelete($id)
  {
    $model          = $this->loadModel($id);
    $product_files = ProductFile::model()->findAllByAttributes(array(
      'productID' => $id
    ));
    if (!empty($product_files)) {
      foreach ($product_files as $product_file) {
        $file         = File::model()->findByPk($product_file->fileID);
        
        if (!empty($file) && file_exists(Yii::app()->basePath . "/../upload/product/post-images/" . $file->filesaved)) {
          @unlink(Yii::getPathOfAlias("webroot") . "/upload/product/post-images/" . $file->filesaved);
          $thumbnails = Product::model()->thumbnails;
          foreach ($thumbnails as $thumbnail) {
            if (file_exists(Yii::app()->basePath . "/../upload/product/thumbs_$thumbnail[0]x$thumbnail[1]/" . $file->filesaved)) {
              @unlink(Yii::getPathOfAlias("webroot") . "/upload/product/thumbs_$thumbnail[0]x$thumbnail[1]/" . $file->filesaved);
            }
          }
          $product_file->delete();
          $file->delete();
        }
      }
    }
    ProductLang::model()->deleteAllByAttributes(array(
      'productID' => $model->id
    ));
    $model->delete();
    
    // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
    if (!isset($_GET['ajax']))
      $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array(
        'index'
      ));
  }
  
  /**
   * Manages all models.
   */
  public function actionIndex()
  {
    $model = new Product('search');
    $model->unsetAttributes(); // clear any default values
    if (isset($_GET['Product']))
      $model->attributes = $_GET['Product'];
    
    if (isset($_GET['pageSize'])) {
      Yii::app()->user->setState('pageSize', (int) $_GET['pageSize']);
      unset($_GET['pageSize']); // would interfere with pager and repetitive page size change
    }
      
    $this->render('index', array(
      'model' => $model
    ));
  }
  
  /**
   * Returns the data model based on the primary key given in the GET variable.
   * If the data model is not found, an HTTP exception will be raised.
   * @param integer $id the ID of the model to be loaded
   * @return Product the loaded model
   * @throws CHttpException
   */
  public function loadModel($id)
  {
    $model = Product::model()->findByAttributes(array(
      'id' => $id,
      'deleted' => 0
    ));
    if ($model === null)
      throw new CHttpException(404, 'The requested page does not exist.');
    return $model;
  }
  
  public function loadModelLang($id, $lang)
  {
    $model = ProductLang::model()->findByAttributes(array(
      'productID' => $id,
      'languageID' => $lang
    ));
    if ($model === null)
      $model = new ProductLang();
    return $model;
  }
  
  /**
   * Performs the AJAX validation.
   * @param Product $model the model to be validated
   */
  protected function performAjaxValidation($model)
  {
    if (isset($_POST['ajax']) && $_POST['ajax'] === 'product-form') {
      echo CActiveForm::validate($model);
      Yii::app()->end();
    }
  }
}
?>